<?php
/**
 * Created by PhpStorm.
 * User: Thans
 * Date: 2018/9/22
 * Time: 13:57
 */

namespace app\admin\service;

use app\common\model\UploadGroupModel;
use app\common\model\UploadFileModel;

class UploadGroupService
{
    //获取列表 全部,不分页
    public function getList($data)
    {
        $data['type'] = isset($data['type']) ? $data['type'] : 'type';
        $keyword = isset($data['keyword']) ? $data['keyword'] : '';
        if (!empty($keyword) && $keyword != '') {
            $data['name'] = ['like' => '%' . $keyword . '%'];
        }
        unset($data['keyword']);
        $data['uid'] = cmf_get_uid();
        $list = UploadGroupModel::where($data)->select();
        return ['code' => 1001, 'msg' => '获取成功', 'data' => $list];
    }

    public function index($id)
    {
        if (empty($id)) {
            return ['code' => 4001, 'msg' => '参数错误', 'data' => ''];
        }
        $data['uid'] = cmf_get_uid();
        $data['id'] = $id;
        $res = UploadGroupModel::where($data)->find();
        if ($res) {
            return ['code' => 1001, 'msg' => '获取成功', 'data' => $res];
        }
        return ['code' => 4001, 'msg' => '分组不存在', 'data' => $res];
    }

    //新增
    public function save($data)
    {
        $data['type'] = $data['type'] ?: 'image';
        $data['uid'] = cmf_get_uid();
        $data['list_order'] = $data['list_order'] ?: '1000';
        if (empty($data['name'])) {
            return ['code' => 4001, 'msg' => '缺少分组名称', 'data' => ''];
        }
        $res = UploadGroupModel::create($data, true);
        if ($res) {
            return ['code' => 1001, 'msg' => '新增成功', 'data' => $res];
        }
        return ['code' => 4001, 'msg' => '新增失败', 'data' => ''];
    }

    //删除
    public function delete($id)
    {
        $group = UploadGroupModel::where('uid', cmf_get_uid())->get($id);
        if ($group->delete_time || !$group) {
            return ['code' => 4001, 'msg' => '未找到对应数据', 'data' => ''];
        }
        //判断文件组是否存在文件，存在则无法删除
        $res = UploadFileModel::where('gid', $id)->find();
        if ($res) {
            return ['code' => 4001, 'msg' => '文件组存在文件，无法删除', 'data' => ''];
        }
        $res = $group->delete();
        if ($res) {
            return ['code' => 1001, 'msg' => '删除成功', 'data' => ''];
        }
        return ['code' => 4001, 'msg' => '删除失败', 'data' => ''];
    }

    //更新
    public function update($id, $data)
    {
        $map['uid'] = cmf_get_uid();
        $res = UploadGroupModel::where($map)->update($data);
        if ($res) {
            return ['code' => 1001, 'msg' => '更新成功', 'data' => $data];
        }
        return ['code' => 4001, 'msg' => '更新失败', 'data' => ''];
    }
}